<?php

/**
 * 用于调用微信高级接口api的类
 */
class WechatAdvanceAPI{
	
	private static function get_access_token(){
		$token = $_REQUEST['token'];
		if(empty($token)){
			$token=session('token');
		}
		
		$access_token=S($token.'access_token');
		if($access_token){
			return $access_token;
		}else{
			$where['token'] = $token;
			$api=M('Diymen_set')->where($where)->find();
			if($api['appid']==false||$api['appsecret']==false){
				//$this->error('必须先填写【AppId】和【 AppSecret】');
				exit();
			}
			// 获取access_token
			$url_get='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$api['appid'].'&secret='.$api['appsecret'];
			/* $result=file_get_contents($url_get);
			if(empty($result)){
				$result=WechatAdvanceAPI::https_get($url_get);
			} */
			$result=WechatAdvanceAPI::https_get($url_get);
			$json=json_decode($result);
			$access_token=$json->access_token;
			S($token.'access_token',$access_token,2000);
			return $access_token;
		}
	}
	
	/**
	 * 创建永久二维码
	 * @param string $sceneId
	 */
	static function CreateQRUnLimitSence($sceneId) {
		if($sceneId > '100000' || $sceneId < '1') {
			return false;
		}
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
		$arr=array(
				'action_name'=>'QR_LIMIT_SCENE',
				'action_info'=>array(
						'scene'=>array(
							'scene_id'=>$sceneId
		)));
		$data=urldecode(json_encode($arr));
		$tmpJson=WechatAdvanceAPI::https_post($url,$data);
		//var_dump($data);
		//var_dump($tmpJson);
		if($tmpJson===false){
			return false;
		}
		$json=json_decode($tmpJson);
		return $json;
	}
	
	
	/**
	 * 创建临时二维码
	 * @param unknown $sceneId
	 * @param unknown $expireTime
	 */
	static function CreateQRLimitSence($sceneId,$expireTime) {
		if($sceneId < '1') {
			return false;
		}
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
		$arr=array(
				'expire_seconds'=>$expireTime,
				'action_name'=>'QR_SCENE',
				'action_info'=>array(
						'scene'=>array(
							'scene_id'=>$sceneId
		)));
		$data=urldecode(json_encode($arr));
		$tmpJson=WechatAdvanceAPI::https_post($url,$data);
		//var_dump($data);
		//var_dump($tmpJson);
		if($tmpJson===false){
			return false;
		}
		$json=json_decode($tmpJson);
		return $json;
	}
	
	
	/**
	 * 关注者列表接口，拉取所有关注者
	 */
	static function GetUserList(){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token;
		$tmpJson=WechatAdvanceAPI::https_get($url);
		if($tmpJson===false){
			return false;
		}
		$json=json_decode($tmpJson);
		return $json;
	}
	
	/**
	 * 用户基本信息,拉取一个用户的信息
	 */
	static function GetUserInfo($openId){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openId.'&lang=zh_CN';
		$tmpJson=WechatAdvanceAPI::https_get($url);
		if($tmpJson===false){
			return false;
		}
		$json=json_decode($tmpJson);
		return $json;
	}
	
	/*
	 * 分组管理相关接口=================
	 */
	
	/**
	 * 创建分组接口
	 * 
	 * @param string $groupName
	 *        	分组名称，中文需要进行urlencode编码urlencode('中文')
	 * @return json 接口返回结果
	 */
	static function CreateGroup($groupName){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/groups/create?access_token='.$access_token;
		
		$arr=array(
				'group'=>array(
						'name'=>$groupName));
		$data=urldecode(json_encode($arr));
		
		return json_decode(WechatAdvanceAPI::https_post($url,$data));
	}
	
	/**
	 * 获取用户所有分组
	 * 
	 * @return json 接口返回结果
	 */
	static function GetGroups(){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/groups/get?access_token='.$access_token;
		
		return json_decode(WechatAdvanceAPI::https_get($url));
	}
	
	/**
	 * 获取用户所在分组
	 * 
	 * @param string $openId        	
	 * @return json 接口返回结果
	 */
	static function GetUserGroup($openId){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/groups/getid?access_token='.$access_token;
		
		$arr=array(
				'openid'=>$openId);
		$data=json_encode($arr);
		
		return json_decode(WechatAdvanceAPI::https_post($url,$data));
	}
	
	/**
	 * 修改分组名
	 * 
	 * @param int $groupId        	
	 * @param string $groupName
	 *        	中文需要进行urlencode编码urlencode('中文')
	 * @return json 接口返回结果
	 */
	static function UpdateGroupName($groupId,$groupName){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/groups/update?access_token='.$access_token;
		
		$arr=array(
				'group'=>array(
						'id'=>$groupId,
						'name'=>$groupName));
		$data=urldecode(json_encode($arr));
		
		return json_decode(WechatAdvanceAPI::https_post($url,$data));
	}
	
	/**
	 * 移动用户分组
	 * 
	 * @param string $openId        	
	 * @param int $groupId        	
	 * @return json 接口返回结果
	 */
	static function UpdateUserGroup($openId,$groupId){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token='.$access_token;
		
		$arr=array(
				'openid'=>$openId,
				'to_groupid'=>$groupId);
		$data=json_encode($arr);
		
		return json_decode(WechatAdvanceAPI::https_post($url,$data));
	}
	
	/* static function SaveGroupInfo($token){
		$gpinfo=WechatAdvanceAPI::GetGroups();
		$gpinfos=$gpinfo->groups;
		
		if(!$token){
			$token=session('token');
		}
		if($gpinfos){
			$model=M('subscribe_group');
			
			foreach($gpinfos as $gp){
				$isnew=false;
				$where['token']=$token;
				$where['groupid']=$gp->id;
				$data=$model->where($where)->find();
				if($data==null){
					$isnew=true;
				}
				$data['token']=$token;
				$data['groupid']=$gp->id;
				$data['groupname']=$gp->name;
				$data['groupcount']=$gp->count;
				if($isnew){
					$model->add($data);
				}else{
					$model->where($where)->save($data);
				}
			}
			return true;
		}else{
			return false;
		}
	} */
	
	/*
	 * 分组管理相关接口=================end
	 */
	
	/**
	 * @param unknown $tos  发送对象
	 * @param unknown $content  发送内容
	 * @param unknown $msgtype 发送类型 1文本信息；2图文信息
	 * @param unknown $sendtype 发送方式，1 openid群发；2 分组群发
	 */
	static function PostGroupMsg($tos,$content, $msgtype,$sendtype){
		$access_token=WechatAdvanceAPI::get_access_token();
		//https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN //分组群发
		//https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN //openid群发
		
		$arr = array();
		
		if($sendtype == 1){
			$url = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='.$access_token;
			$arr['touser'] = $tos;
		}else{
			$url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$access_token;
			$arr['filter'] = array(
				'is_to_all'=>false,
				'group_id'=>$tos,
			);
		}
		
		if($msgtype == 1){
			$arr['msgtype'] = 'text';
			$arr['text'] = array('content'=>$content);
		}else{
			$arr['mpnews'] = array('media_id'=>$content);
			$arr['msgtype'] = 'mpnews';
			
		}
		$data=urldecode(json_encode($arr));
		//return $data;
		return json_decode(WechatAdvanceAPI::https_post($url,$data));
	}
	
	static function GetMediaList(){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token='.$access_token;
		
		$arr=array(
			'type'=>'news',
			'offset'=>0,
			'count'=>20,
		);
		$data=json_encode($arr);
		return json_decode(WechatAdvanceAPI::https_post($url,$data),true);
		//return WechatAdvanceAPI::https_post($url,$data);
	}
	
	
	/**
	 * 客服接口，主动发送消息（需48小时内互动过）
	 * 
	 * @param array $content
	 *        	消息内容,如array('content'=>'hello'),中文需要进行urlencode编码array('content'=>urlencode('中文'))
	 * @param string $touser        	
	 * @param string $msgtype        	
	 * @return boolean
	 */
	static function PostMsg($content,$touser,$msgtype='text'){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
		
		$arr=array(
				'touser'=>$touser,
				'msgtype'=>$msgtype,
				'text'=>$content);
		$data=urldecode(json_encode($arr));
		
		$tmpjson=WechatAdvanceAPI::https_post($url,$data);
		
		if($tmpjson===false){
			return false;
		}
		
		$json=json_decode($tmpjson);
		
		if($json->errcode==0){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 调用语义识别接口
	 * @param unknown $content
	 * @param unknown $openid
	 * @return Ambigous <mixed, boolean>
	 */
	static function Semantic($content, $openid){
		$access_token=WechatAdvanceAPI::get_access_token();
		$url='https://api.weixin.qq.com/semantic/semproxy/search?access_token='.$access_token;
		Log::write('url='.$url, LOG::INFO);

		//经过多次测试，只要出入经纬度，则会报700009错误，请求语义服务失败
		/*
		$loc_time = M('wxuserloc')->where(array('wechat_id'=>$openid))->max('loc_time');
		
		if($loc_time !=  null){
			Log::write("成功获取到用户的有效地理位置信息",LOG::INFO);
			$wxuserloc  = M('wxuserloc')->where(array('wechat_id'=>$openid, 'loc_time'=>$loc_time))->find();
			$x = $wxuserloc['location_x'];
			$y = $wxuserloc['location_y'];
		}
		Log::write('sql='.M('wxuserloc')->getLastSql(), LOG::INFO);
		Log::write('longitude='.$x.', latitude='.$y, LOG::INFO);
		*/
		$location = M('subscriber')->where(array('openid'=>$openid))->find();
		if($location['province'] == "北京" || $location['province'] == "上海" || $location['province'] == "天津" || 
			$location['province'] == "重庆" || $location['province'] == "香港" || $location['province'] == "澳门"){
			$city=$location['province'];
		}else if(empty($location['city'])){
			$city='上海';
		}else{
			$city=$location['city'];
		}
		Log::write('user city='.$city, LOG::INFO);
		
		$api=M('Diymen_set')->where($where)->find();
		
		$arr=array(
				"query"=>$content,
				"city"=>$city,
				"category"=>"hotel",
				"appid"=>$api['appid'],
				"uid"=>$openid
				);
		$data=urldecode(json_encode($arr));
		Log::write('data='.$data, LOG::INFO);
		
		$tmpjson=WechatAdvanceAPI::https_post($url,$data);
		Log::write('语义识别结果：'.$tmpjson, LOG::INFO);
		
		return $tmpjson;
	}
	
	/**
	 * 向一个https提交post数据
	 * 
	 * @param unknown $url        	
	 * @param unknown $data        	
	 * @return mixed
	 */
	static function https_post($url,$data){
		$curl=curl_init(); // 启动一个CURL会话
		curl_setopt($curl,CURLOPT_URL,$url); // 要访问的地址
		curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0); // 对认证证书来源的检查
		curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,2); // 从证书中检查SSL加密算法是否存在
		                                               // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
		                                               // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
		                                               // curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
		                                               // curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
		curl_setopt($curl,CURLOPT_POSTFIELDS,$data); // Post提交的数据包
		curl_setopt($curl,CURLOPT_TIMEOUT,30); // 设置超时限制防止死循环
		                                         // curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); // 获取的信息以文件流的形式返回
		$tmpInfo=curl_exec($curl); // 执行操作
		if(curl_errno($curl)){
			// echo 'Errno'.curl_error($curl);//捕抓异常
			return false;
		}
		curl_close($curl); // 关闭CURL会话
		return $tmpInfo; // 返回数据
	}
	
	/**
	 * 向https提交get数据
	 */
	static function https_get($url){
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_TIMEOUT,60); // 设置超时限制防止死循环
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$result=curl_exec($ch);
		if(curl_errno($ch)){
			echo 'Errno'.curl_error($ch); // 捕抓异常
			return false;
		}
		curl_close($ch);
		return $result;
	}
}
?>